package com.gitee.huxing.course;

import cn.hutool.core.date.DateUtil;
import com.gitee.huxing.course.service.DemoResolver;
import com.gitee.huxing.framework.core.ServiceInvoker;
import com.gitee.huxing.framework.core.ServiceProviderDesc;
import com.gitee.huxing.framework.core.ServiceResolver;
import com.gitee.huxing.framework.core.module.RequestInfo;
import com.gitee.huxing.framework.core.module.ResponseInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;

@Slf4j
@RestController
@SpringBootApplication
public class RpcDemoProviderApplication implements CommandLineRunner {

    @Autowired
    ServiceInvoker invoker;

    public static void main(String[] args) {
        SpringApplication.run(RpcDemoProviderApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("RPC服务启动: {}", DateUtil.now());
    }

    /**
     * @Description: 注册客户服务
     * @Author: huxing
     * @param client    客户端
     * @param service
     * @Date: 2021/10/3 下午4:01
     **/
    private static void registerService(CuratorFramework client, String service)throws Exception{
        ServiceProviderDesc userServiceDesc = ServiceProviderDesc.builder()
                .host(InetAddress.getLocalHost().getHostAddress())
                .port(8091).serviceClass(service).build();
        try {
            if ( null == client.checkExists().forPath("/" + service)) {
                client.create().withMode(CreateMode.PERSISTENT).forPath("/" + service, "service".getBytes());
            }
        } catch (Exception ex){
            ex.printStackTrace();
        }

        client.create().withMode(CreateMode.EPHEMERAL).
                forPath( "/" + service + "/" + userServiceDesc.getHost() + "_"
                        + userServiceDesc.getPort(), "provider".getBytes());
    }

    @PostMapping("/")
    public ResponseInfo invoke(@RequestBody RequestInfo request) {
        return invoker.invoke(request);
    }

    @Bean
    public ServiceInvoker createInvoker(@Autowired ServiceResolver resolver){
        return new ServiceInvoker(resolver);
    }

    @Bean
    public ServiceResolver createResolver(){
        return new DemoResolver();
    }
}
